package com.rupertjones.globalcron.domain;

import com.rupertjones.globalcron.util.TypeConverter;
import org.apache.log4j.Logger;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
@Entity
@Table(name = "setting")
public class Setting extends BaseEntity {

    private static final Logger LOG = Logger.getLogger(Setting.class);

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "type")
    @Enumerated(EnumType.STRING)
    private SettingType type;

    @Column(name = "name")
    private String name;

    @Column(name = "value_type")
    private String valueType;

    @Column(name = "setting_value")
    private String value;

    @Column
    private String description;

    @Override
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public int getId() {
        return this.id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public SettingType getType() {
        return type;
    }

    public String getValueType() {
        return valueType;
    }

    public void setValueType(String valueType) {
        this.valueType = valueType;
    }

    public void setType(SettingType type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public boolean isValueValid(String value) {
        try {
            TypeConverter.convert(value, getValueTypeAsClass());
            return true;
        } catch (RuntimeException rte) {
            LOG.warn(rte);
            return false;
        }
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Class getValueTypeAsClass() {
        try {
            return Class.forName(getValueType());
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
}
